package com.hfjyz.registration.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import com.hfjyz.registration.command.AdminLoginCommand;
import com.hfjyz.registration.contants.ExamContants;
import com.hfjyz.registration.service.RegistService;

public class AdminLoginController extends SimpleFormController {
	private RegistService registService;

	/**
	 * @return the registService
	 */
	public RegistService getRegistService() {
		return registService;
	}

	/**
	 * @param registService
	 *            the registService to set
	 */
	public void setRegistService(RegistService registService) {
		this.registService = registService;
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		AdminLoginCommand cmd = (AdminLoginCommand) command;
		if (!errors.hasErrors()) {
			registService.loggin(request, ExamContants.LOGING_TYPE_INFO,
					(Integer) null, ExamContants.LOGING_USER_TYPE_MANAGE,
					cmd.getAdminId(), ExamContants.LOGING_OP_TYPE_LOGING,
					"管理员登录");
			try {
				registService.adminLogin(cmd, errors);
			} catch (Exception ex) {

				registService.loggin(request, ExamContants.LOGING_TYPE_ERROR,
						(Integer) null, ExamContants.LOGING_USER_TYPE_MANAGE,
						cmd.getAdminId(), ExamContants.LOGING_OP_TYPE_LOGING,
						"管理员登录失败");
				throw ex;
			}
		}
		if (errors.hasErrors()) {
			registService.loggin(request, ExamContants.LOGING_TYPE_WARNING,
					(Integer) null, ExamContants.LOGING_USER_TYPE_MANAGE,
					cmd.getAdminId(), ExamContants.LOGING_OP_TYPE_LOGING,
					"管理员登录验证失败");
			return new ModelAndView(getFormView(), errors.getModel());
		}
		request.getSession().setAttribute("AdminInfo", cmd);
		RedirectView rv = new RedirectView("adminInit.action");
		return new ModelAndView(rv, errors.getModel());
	}
}
